package com.demo.intercept;

import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * FileName: DemoInterceptor
 *
 * @author: xunyong
 * Date:     2019/5/14 16:27
 * Description: 接口拦截器
 */
public class DemoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle 运行了这里");
        //判断如果不是请求control方法直接返回true
        if(! (handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        //判断访问的control是否添加LoginRequired注解
        Intercept loginRequired =  method.getMethodAnnotation(Intercept.class);
        boolean required = true;
        if (loginRequired != null){
            required = loginRequired.required();
            //如果添加了requird注解，则在消息请求头中查看token是否存在
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)) {
                return false;
            }
            System.out.println("token----------------:"+token);
            // 从 http 请求头中取出 token,获取token的内容并解析，然后判断用户是否存在、是否登录、是否在线超时等
            if ("token".equals(token)){
                return true;
            }else {
                throw new Exception("用户没有登录，登录超时等");
            }
        }else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }



}